import React, { useState, useRef } from 'react';
import { Card, Input, Button, Upload, message } from 'antd';
import type { UploadProps } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';

const { TextArea } = Input;
const { Dragger } = Upload;

const ReplaceProduct: React.FC = () => {
  const [description, setDescription] = useState<string>('');
  const [imageUrl, setImageUrl] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [tourVisible, setTourVisible] = useState(false);
  
  // Tour相关的ref引用
  const uploadRef = useRef<HTMLDivElement>(null);
  const descriptionRef = useRef<HTMLDivElement>(null);
  const generateRef = useRef<HTMLButtonElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);
  
  // 组织所有ref为一个对象
  const tourRefs = {
    upload: uploadRef,
    description: descriptionRef,
    generate: generateRef,
    result: resultRef,
  };
  
  // 显示导览
  const showTour = () => {
    // 添加短暂延迟确保DOM已渲染
    setTimeout(() => setTourVisible(true), 100);
  };
  
  // Tour步骤配置
  const tourSteps = [
    {
      key: 'upload',
      title: '上传商品图片',
      description: '点击或拖拽文件上传您需要替换的商品图片',
    },
    {
      key: 'description',
      title: '填写描述',
      description: '描述您想要替换的商品和背景场景，帮助AI更好理解您的需求',
    },
    {
      key: 'generate',
      title: '生成按钮',
      description: '点击此按钮开始生成替换商品图片',
    },
    {
      key: 'result',
      title: '生成结果',
      description: '下方区域将显示生成的替换商品图片，您可以下载或重新生成',
    },
  ];

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    action: '/api/upload',
    onChange(info) {
      const { status } = info.file;
      if (status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
        setImageUrl(URL.createObjectURL(info.file.originFileObj as File));
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
  };

  const handleGenerate = () => {
    if (!description || !imageUrl) {
      message.warning('请填写描述并上传图片');
      return;
    }

    setLoading(true);
    // 模拟AI生成过程
    setTimeout(() => {
      message.success('商品替换图片生成成功');
      setLoading(false);
    }, 3000);
  };

  return (
    <>
      <div className="p-4">
        <h2 className="text-xl font-bold mb-4" style={{ display: 'flex', alignItems: 'center' }}>
          替换商品
          <TourGuideButton onClick={showTour} />
        </h2>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Card title="上传商品图片" className="h-full">
          <div ref={uploadRef}>
            <Dragger {...uploadProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                支持单个图片文件上传，用于商品替换
              </p>
            </Dragger>
          </div>
        </Card>
        <Card title="生成参数" className="h-full">
          <div ref={descriptionRef}>
            <TextArea
              rows={4}
              placeholder="请描述您想要替换的商品和背景场景"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="mb-4"
            />
          </div>
          <Button ref={generateRef} style={{ marginTop: '16px' }} type="primary" onClick={handleGenerate} loading={loading} block>
            生成替换商品图片
          </Button>
        </Card>
      </div>
      {imageUrl && (
        <Card title="生成结果" className="mt-4">
          <div ref={resultRef} className="flex justify-center overflow-hidden p-2">
            <img 
              src={imageUrl} 
              alt="替换商品结果" 
              className="max-w-full max-h-[500px] object-contain w-full h-auto" 
              style={{ 
                maxWidth: '100vw', 
                maxHeight: '60vh',
                margin: '0 auto'
              }} 
            />
          </div>
          <div className="flex justify-center mt-4">
            <Button className="mr-2">下载图片</Button>
            <Button type="primary">重新生成</Button>
          </div>
        </Card>
      )}
    </div>
    
    <CommonTour
      open={tourVisible}
      onClose={() => setTourVisible(false)}
      steps={tourSteps}
      targetRefs={tourRefs}
    />
  </>
  );
};

export default ReplaceProduct;